<?php

namespace App\Http\Controllers;

use App\Filters\QuestionFilter;
use App\Http\Middleware\Authenticate;
use App\Http\Middleware\MustVerifyEmail;
use App\Models\Category;
use App\Models\Question;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class QuestionsController extends Controller
{
    //


    /**
     * QuestionsController constructor.
     */
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['show', 'index']]);
        $this->middleware('must-verify-email')->except(['index', 'show']);
    }

    public function index(QuestionFilter $filters,User $user)
    {
        $questions = Question::published()->filter($filters)->paginate(20);
        array_map(function (&$item) {
            return $this->appendAttribute($item);
        }, $questions->items());

        $activeUsers = $user->getActiveUsers();
        return view('questions.index', compact('questions', 'activeUsers'));
    }

    public function create(Question $question)
    {
        $categories = Category::all();
        return view('questions.create', compact('categories', 'question'));
    }

    public function store()
    {

        $this->validate(request(), [
            'title' => 'required',
            'content' => 'required',
            'category_id' => 'required|exists:categories,id',
        ]);
        $question = Question::create([
            'user_id' => auth()->id(),
            'category_id' => request('category_id'),
            'title' => request('title'),
            'content' => request('content'),
        ]);

        return redirect("/drafts")->with('flash', '创建成功！');
    }


    public function show(Question $question)
    {
        $question = Question::published()->findOrFail($question->id);
        $question = $this->appendAttribute($question);
        $answers = $question->answers()->paginate(20);
        array_map(function (&$item) {
            return $this->appendVotedAttribute($item);
        }, $answers->items());

        return view('questions.show', compact('question', 'answers'));
    }

    public function appendAttribute($item)
    {
        $user = auth()->user();

        $item->isVotedUp = $item->isVotedUp($user);
        $item->isVotedDown = $item->isVotedDown($user);
        $item->isSubscribedTo = $item->isSubscribedTo($user);
        $item->comments = $item->comments();
        return $item;
    }

}
